<?php
namespace app\common\library\util;
require_once dirname(__FILE__).'/vendor/autoload.php';
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;

class MyWebSocketServer implements MessageComponentInterface 
{
    protected $clients;
    protected $seed;
    protected $ts;
    public static $token;

    public function __construct($seed,$ts) {
        $this->clients = new \SplObjectStorage;
        $this->seed = $seed;
        $this->ts = $ts;
    }

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        // 处理收到的消息
        // …
        if($msg){
            self::$token = urldecode($msg);
            return self::$token;
        }
        // 向所有客户端发送消息
        foreach ($this->clients as $client) {
            $messageData = [
                'seed'=>$this->seed,
                'ts'=>$this->ts,
            ];
            $client->send(json_encode($messageData));
        }
    }

    public function onClose(ConnectionInterface $conn) {
        $this->clients->detach($conn);
        echo "Connection {$conn->resourceId} has disconnected\n";
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }
}

